<template>
  <div>
    <!--数据表单-->
    <el-form label-width="150px" :model="formData" size="mini">
      <el-row>
        <!--Category-->
        <el-col :span="12">
          <el-form-item label="Category">
            <el-input
              v-model="formData.category"
              v-blur:category="formData"
              clearable
              :placeholder="$t('input.placeholder')"
            />
          </el-form-item>
        </el-col>
        <!--父节点-->
        <el-col :span="12">
          <el-form-item label="父节点">
            <el-popover v-model="popoverVisible" placement="bottom" width="260">
              <el-input slot="reference" v-model="nodeName" clearable />
              <el-tree
                :data="treeData"
                :props="defaultProps"
                @node-click="handleNodeClick"
              ></el-tree>
            </el-popover>
          </el-form-item>
        </el-col>
        <!--Order-->
        <el-col :span="12">
          <el-form-item label="Order">
            <el-input-number
              v-model="formData.order"
              controls-position="right"
              :min="0"
            ></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span style="display: block;text-align: center;margin-top: 5px">
      <!--取消按钮-->
      <el-button size="medium" @click="cancel">{{ $t('button.cancel') }}</el-button>
      <!--保存按钮-->
      <el-button :loading="isRequesting" size="medium" type="primary" @click="save">
        {{ $t('button.save') }}
      </el-button>
    </span>
  </div>
</template>
<script>
import { cbomGroupAdd } from '@/api/cbom/group'
export default {
  name: 'CbomGroupAdd',
  props: {
    treeData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      /** 表单数据 */
      formData: {
        category: '',
        parentId: '',
        order: 0
      },
      popoverVisible: false,
      defaultProps: {
        children: 'children',
        label: 'category'
      },
      /** 选中的节点名称 */
      nodeName: '',

      isRequesting: false
    }
  },

  methods: {
    cancel() {
      this.$emit('cancel')
    },

    async save() {
      try {
        this.isRequesting = true
        await cbomGroupAdd(this.formData, {
          msgSuccess: true,
          msgError: true
        })
        this.$emit('save')
        this.cancel()
      } catch (error) {
        console.log(error)
      } finally {
        this.isRequesting = true
      }
    },

    handleNodeClick(data) {
      this.popoverVisible = false
      this.nodeName = data.category
      this.formData.parentId = data.id
    }
  }
}
</script>
